package com.zy.baselib.tools;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.zy.baselib.annotations.Ignore;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Convert {


    public static <S, R> List<R> convertToResultList(@NonNull List<S> source, @NonNull Class<S> sClass, @NonNull Class<R> rClass) {
        List<R> results = new ArrayList<R>();
        if(source == null)
        return results;
        try {
            for (S one : source) {
                Constructor<R> constructor = rClass.getConstructor(sClass);
                results.add(constructor.newInstance(one));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public static <S, R> List<R> convertToResultList(@NonNull List<S> source, @NonNull Class<R> rClass) {
        List<R> results = new ArrayList<R>();
        if(source == null)
            return results;
        try {
            for (S one : source) {
                Constructor<R> constructor = rClass.getConstructor(one.getClass());
                results.add(constructor.newInstance(one));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public static @NonNull <S> Map<String, Object> convertToMap(S s, @NonNull Map<String, String> nameMap) {
        Map<String, Object> map = new HashMap<>();
        Field[] declaredFields = s.getClass().getDeclaredFields();
        if(declaredFields.length == 0) return map;
        for(Field field: declaredFields) {
            field.setAccessible(true);
            Ignore annotation = field.getAnnotation(Ignore.class);
            if(annotation != null) continue;
            String name = field.getName();
            String key = nameMap.get(name);
            if(TextUtils.isEmpty(key)) continue;
            try {
                Object o = field.get(s);
                map.put(key, o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

